<template>
  <div class="profile">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">个人信息 - 修改密码</div>
      </template>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="原密码" prop="old_password">
          <el-input v-model="form.old_password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="新密码" prop="new_password">
          <el-input v-model="form.new_password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input v-model="form.confirm_password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="onSubmit">保存</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { api } from '../api/client'

const formRef = ref()
const loading = ref(false)
const form = reactive({
  old_password: '',
  new_password: '',
  confirm_password: '',
})

const rules = {
  old_password: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  new_password: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  confirm_password: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (_: any, value: string, callback: Function) => {
        if (value !== form.new_password) callback(new Error('两次输入的密码不一致'))
        else callback()
      },
      trigger: 'blur',
    },
  ],
}

function onReset() {
  form.old_password = ''
  form.new_password = ''
  form.confirm_password = ''
}

async function onSubmit() {
  // @ts-ignore
  await formRef.value?.validate(async (valid: boolean) => {
    if (!valid) return
    loading.value = true
    try {
      await api.post('/auth/change-password', {
        old_password: form.old_password,
        new_password: form.new_password,
      })
      ElMessage.success('密码已更新')
      onReset()
    } catch (e: any) {
      ElMessage.error(e?.response?.data?.detail || '修改密码失败')
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
.profile { padding: 24px; }
.profile-card { max-width: 600px; margin: 0 auto; }
.card-header { font-weight: 600; }
</style>